# Copyright (C) 2007 Laszlo Pandy <laszlok2@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import gtk
import gobject
import pango
import datetime
Date = datetime.date

from AdventureMoney.core import Utils
from AdventureMoney.core import ShareProfile
import InterfaceUtils
import CalendarEntry as Cal
import AdvancedShareWidget
import NewPaymentDialog
import EditPaymentDialog

class PaymentView(gtk.Frame):
	def __init__(self, account, mainWindow):
		gtk.Frame.__init__(self)
		self.wTree = InterfaceUtils.GetGladeTree("PaymentViewHolder")
		
		signals = {
			"OnNewPayment"		: self.OnNewPayment,
			"OnEditPayment"		: self.OnEditPayment,
			"OnDeletePayment"	: self.OnDeletePayment,
			"OnCategoryChanged"	: self.OnFilterChange,
			"OnPaidByChanged"	: self.OnFilterChange,
			"OnFilterEntryChanged"	: self.OnFilterChange,
		}
		
		self.wTree.signal_autoconnect(signals)
		
		self.account = account
		self.account.connect("people", self.UpdateInterface)
		self.account.connect("categories", self.UpdateInterface)
		self.account.connect("bills", self.UpdateInterface)
		
		self.mainWindow = mainWindow
		self.updating = False
		
		self.vbox = self.wTree.get_widget("PaymentViewVBox")
		self.wTree.get_widget("PaymentViewHolder").remove(self.vbox)
		self.add(self.vbox)
		
		self.dateHBox = self.wTree.get_widget("DateEntryHBox")
		self.categoryCombo = self.wTree.get_widget("CategoryCombo")
		self.paidByCombo = self.wTree.get_widget("PaidByCombo")
		self.filterEntry = self.wTree.get_widget("FilterEntry")
		self.treeview = self.wTree.get_widget("BillsTreeView")
		
		self.categoryModel = gtk.ListStore(str, object)
		self.categoryCombo.set_model(self.categoryModel)
		self.categoryCombo.set_column_span_column(0)
		self.paidByModel = gtk.ListStore(str, object)
		self.paidByCombo.set_model(self.paidByModel)
		self.paidByCombo.set_column_span_column(0)
		
		year = Date.today().year
		self.fromDateEntry = Cal.CalendarEntry()
		self.toDateEntry = Cal.CalendarEntry()
		
		self.dateHBox.pack_start(self.fromDateEntry)
		self.dateHBox.reorder_child(self.fromDateEntry, 1)
		self.dateHBox.pack_start(self.toDateEntry)
		self.dateHBox.reorder_child(self.toDateEntry, 3)
		
		self.fromDateEntry.connect("date_changed", self.OnFilterChange)
		self.toDateEntry.connect("date_changed", self.OnFilterChange)
		
		#ID, date, value, description, category, paidBy, sharedBy, category-Style
		self.model = gtk.ListStore(int, str, str, str, str, str, str, pango.Style)
		self.treeview.set_model(self.model)
		
		self.treeview.insert_column_with_attributes(-1, "Date", gtk.CellRendererText(), text=1)
		self.treeview.insert_column_with_attributes(-1, "Value", gtk.CellRendererText(), text=2)
		self.treeview.insert_column_with_attributes(-1, "Description", gtk.CellRendererText(), text=3)
		self.treeview.insert_column_with_attributes(-1, "Category", gtk.CellRendererText(), text=4, style=7)
		self.treeview.insert_column_with_attributes(-1, "Paid By", gtk.CellRendererText(), text=5)
		self.treeview.insert_column_with_attributes(-1, "Shared By", gtk.CellRendererText(), text=6)
		
		self.show_all()
		
	def OnNewPayment(self, widget=None):
		NewPaymentDialog.NewPaymentDialog(self.mainWindow, self.account, self.NewPaymentCb)
		
	def NewPaymentCb(self, ID, value, date, description, comments, paidBy, sharedOrCate):
		if type(sharedOrCate) == str:
			sharedOrCate = self.account.findCategory(sharedOrCate)
			if sharedOrCate.getPaidBy():
				paidBy = None
		elif type(sharedOrCate) == list:
			shared = []
			for i in sharedOrCate:
				person = self.account.findPerson(i)
				shared.append(person)
			sharedOrCate = shared
		
		if paidBy:
			paidBy = self.account.findPerson(paidBy)
			
		self.account.addBill(value, date, paidBy, sharedOrCate, description, comments)
		
	def OnEditPayment(self, widget):
		EditPaymentDialog.EditPaymentDialog(self.mainWindow, self.account, self.EditPaymentCb, self.GetSelectedID())
		
	def EditPaymentCb(self, ID, value, date, description, comments, paidBy, sharedOrCate):
		if type(sharedOrCate) == str:
			sharedOrCate = self.account.findCategory(sharedOrCate)
			if sharedOrCate.getPaidBy():
				paidBy = None
		elif type(sharedOrCate) == list:
			shared = []
			for i in sharedOrCate:
				person = self.account.findPerson(i)
				shared.append(person)
			sharedOrCate = shared
		
		if paidBy:
			paidBy = self.account.findPerson(paidBy)
			
		self.account.changeBill(ID, value, date, paidBy, sharedOrCate, description, comments)
		
	def OnDeletePayment(self, widget):
		ID = self.GetSelectedID()
		if ID != None:
			self.account.removeBill(ID)
		
	def OnFilterChange(self, widget):
		self.UpdateModel()
	
	def GetSelectedID(self):
		path = self.treeview.get_cursor()[0]
		if path:
			ID = self.model[path][0]
			return ID
		return None
	
	@InterfaceUtils.UpdatingGUI
	def UpdateInterface(self, widget=None):
		cateIndex = self.categoryCombo.get_active()
		paidIndex = self.paidByCombo.get_active()
		
		self.categoryModel.clear()
		self.paidByModel.clear()
		
		self.categoryModel.append(("Any", None))
		for category in self.account.getCategories():
			self.categoryModel.append((str(category), category))
			
		self.paidByModel.append(("Anyone", None))
		for person in self.account.getPeople():
			self.paidByModel.append((str(person), person))
		
		if not 0 <= cateIndex < len(self.categoryModel):
			cateIndex = 0
		self.categoryCombo.set_active(cateIndex)
		
		if not 0 <= paidIndex < len(self.paidByModel):
			paidIndex = 0
		self.paidByCombo.set_active(paidIndex)
		
		self._UpdateModel()
	
	@InterfaceUtils.UpdatingGUI
	def UpdateModel(self):
		self._UpdateModel()
		
	def _UpdateModel(self):
		path = self.treeview.get_cursor()[0]
		
		self.model.clear()
		
		for bill in self.GetFilteredBills():
			value = str(bill.getValue())
			date = str(bill.getDate())
			details = str(bill.getDetails())
			category = str(bill.getCategory())
			paid = str(bill.getPaidBy())
			cateStyle = pango.STYLE_NORMAL
			shared = bill.getSharedBy().getPrettyString()
			
			if not category:
				category = ""
				
			self.model.append((bill.ID, date, value, details, category, paid, shared, cateStyle))
			
		if path and len(self.model):
			if path[0] >= len(self.model):
				index = len(self.model) - 1
			else:
				index = path[0]
			self.treeview.set_cursor( (index,) )
	
	def GetFilteredBills(self):
		billsList = self.account.getBills()
		
		cateIter = self.categoryCombo.get_active_iter()
		if cateIter:
			cate = self.categoryModel.get_value(cateIter, 1)
			if cate:
				billsList.filterByCategory([cate])
		
		paidByIter = self.paidByCombo.get_active_iter()
		if paidByIter:
			person = self.paidByModel.get_value(paidByIter, 1)
			if person:
				billsList.filterByPaidBy([person])
		
		lowerText = self.fromDateEntry.get_text()
		upperText = self.toDateEntry.get_text()
		if Utils.isValidDateStr(lowerText) and Utils.isValidDateStr(upperText):
			lowerDate = Utils.dateFromStr(lowerText)
			upperDate = Utils.dateFromStr(upperText)
			billsList.filterByDate(lowerDate, upperDate)
			
		
		text = self.filterEntry.get_text()
		if text:
			tokens = [x.strip() for x in text.split() if x.strip()]
			if tokens:
				billsList.filterByAnything(tokens)
			
		return billsList
